package cn.myjerry.server.demo4;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class WebHandler extends DefaultHandler {
	private List<Entity> entityList;
	private List<Mapping> mappingList;
	private Entity entity;
	private Mapping mapping;
	private String beginTag;
	
	private boolean isMapping;

	
	
	@Override
	public void startDocument() throws SAXException {
		// 文档解析开始
		entityList = new ArrayList<>();
		mappingList = new ArrayList<>();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		// 开始元素
		if(null != qName) {
			this.beginTag = qName;
			if(qName.equals("servlet")) {
				this.isMapping = false;
				this.entity = new Entity();
			} else if(qName.equals("servlet-mapping")) {
				this.isMapping = true;
				this.mapping = new Mapping();
			}
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		String str = new String(ch, start, length);
		// 处理内容
		if(null != beginTag) {
			if(!isMapping) {
				if(beginTag.equals("servlet-name")) {
					this.entity.setName(str);
				} else if(beginTag.equals("servlet-class")) {
					this.entity.setClz(str);
				}
			} else {
				if(beginTag.equals("servlet-name")) {
					this.mapping.setName(str);
				} else if(beginTag.equals("url-pattern")) {
					this.mapping.getUslPattern().add(str);
				}
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		// 结束元素
		if(null != qName) {
			if(qName.equals("servlet")) {
				entityList.add(this.entity);
			} else if(qName.equals("servlet-mapping")) {
				mappingList.add(this.mapping);
			}
		}
		this.beginTag = null;
	}
	
	@Override
	public void endDocument() throws SAXException {
		// 文档解析结束
	}
	
	public List<Entity> getEntityList() {
		return entityList;
	}

	public List<Mapping> getMappingList() {
		return mappingList;
	}
	
}
